import React, { useState, useMemo } from 'react';
import { Popover, Checkbox, Space, Button, Modal } from 'antd';
import { ExclamationCircleOutlined, SafetyCertificateOutlined } from '@ant-design/icons';
import QRCode from 'qrcode.react';
import CommonTable from '@/components/CommonTable';
import CommonLoading from '@/components/CommonLoading';
import PeriodDetails from '../PeriodDetails/index';
import PeriodInformation from '../Modals/PeriodInformation';
import ApplyBillPeriod from '../Modals/ApplyBillPeriod';
import CommonTag from '@/components/CommonTag';
import TableRender from '@/components/TableRender';
import { formatAmount } from '@/utils/utils.jsx';
import { getZxlDetailsOp } from '../../service';
import IconFont from '@/components/IconFont';
import styles from '../styles.module.less';

//用于判断筛选条件是否发生了变化
let isFilter = false;

const PeriodTable = ({
  data,
  type,
  pages,
  changePages,
  headerHeight,
  ApplyBillConfig,
  getAdvance,
  getRepayment,
  billState,
  handleFilter,
  handleOkFilter,
  handleSetApplyBillConfig,
  handleApplyDiscount,
  handleRevokeDiscount,
  openDetailPage
}) => {
  const [loading, setLoading] = useState(false);
  //账单明细
  const [detailVisible, setDetailVisible] = useState(false);

  //单行数据
  const [record, setRecord] = useState({});

  //订单状态
  const [orderStatus, setOrderStatus] = useState('');

  //是否展开订单的筛选
  const [visible, setVisible] = useState(false);

  //查看详情
  const [informationVisible, setInformationVisible] = useState(false);

  //   //申请/修改优惠账期
  //   const [ApplyBillConfig, setApplyBillConfig] = useState({
  //     visible: false,
  //     title: '申请优惠账期',
  //     type: 'add',
  //   });

  const [zxlDetail, setDetail] = useState(false);

  //筛选部分的内容
  const showPeriodFilter = () => {
    return (
      <div style={{ width: '140px' }}>
        <div style={{ marginBottom: '8px' }}>优惠账期状态</div>
        <div style={{ marginBottom: '8px' }}>
          <Checkbox.Group
            style={{ width: '100%' }}
            onChange={(val) => {
              handleSelectState(val);
            }}
            value={billState}
          >
            <Space direction="vertical">
              <Checkbox value={'2'}>审核失败</Checkbox>
              <Checkbox value={'0'}>待审核</Checkbox>
              <Checkbox value={'1'}>审核通过</Checkbox>
              <Checkbox value={'3'}>未申请</Checkbox>
            </Space>
          </Checkbox.Group>
        </div>
        <div style={{ textAlign: 'right' }}>
          <Button
            style={{ marginRight: 12 }}
            onClick={() => handleFilterReset(1)}
          >
            重置
          </Button>
          <Button type="primary" onClick={() => handleFilterReset(2)}>
            确定
          </Button>
        </div>
      </div>
    );
  };

  //弹窗的关闭或打开
  const handleFilterOk = (visible) => {
    if (visible) {
      setVisible(true);
    } else {
      setVisible(false);
    }
    if (isFilter) {
      handleOkFilter();
      isFilter = false;
    }
  };

  //点击确定 和重置按钮
  const handleFilterReset = (val) => {
    setVisible(false);
    if (val == 1) {
      //点击重置
      handleOkFilter(1, undefined);
    } else {
      //点击确定
      handleOkFilter();
    }
    isFilter = false;
  };

  //审核状态的选择
  const handleSelectState = (val) => {
    if (!isFilter) {
      isFilter = true;
    }
    handleFilter(val);
  };

  const columns1 = [
    {
      title: '合同编号',
      code: 'contractNo',
      width: 200,
    },
    {
      title: '供应商',
      code: 'storeName',
      width: 100,
    },
    {
      title: '期数',
      code: 'period',
      width: 80,
    },
    {
      title: '出账时间',
      code: 'createTime',
      width: 150,
    },
    {
      title: '最终还款日',
      code: 'repaymentTime',
      width: 150,
    },
    {
      title: '逾期（天）',
      code: 'duePastDayNum',
      width: 100,
    },
    {
      //   title: '出账金额（元）',
      title: (
        <>
          <span>出账金额（元）</span>
          <Popover content={<div style={{ width: '200px' }}>账期应还金额是正数，代表用户需要还款；如果是负数，代表是商户需要退还用户的钱</div>} placement="topLeft" trigger="hover">
            <span style={{ textIndent: '6px', cursor: 'pointer' }}><IconFont type='iconwenhao1' /></span>
          </Popover>
        </>
      ),
      code: 'orderAmount',
      width: 150,
    },
    {
      title: (
        <div style={{ display: 'flex' }}>
          <div>优惠金额（元）</div>
          <Popover
            placement="bottom"
            content={showPeriodFilter()}
            visible={visible}
            onVisibleChange={(val) => handleFilterOk(val)}
            trigger="click"
          >
            <a className="common-color14">
              {billState ? (
                <div className={styles.shuaixuanSelected}>
                  <div className={styles.font10px}>筛选</div>
                </div>
              ) : (
                <div className={styles.shuaixuanWeixuan}>
                  <div className={styles.font10px}>筛选</div>
                </div>
              )}
            </a>
          </Popover>
        </div>
      ),
      code: 'noAuditDiscountAmount',
      width: 160,
      render: (text, record) => (
        <div>
          <div>{text}</div>
          <div>
            {record.disState == '0' ? <CommonTag type="daishenhe" /> : ''}
            {record.disState == '1' ? <CommonTag type="shenhetongguo" /> : ''}
            {record.disState == '2' ? <CommonTag type="shenheshibai" /> : ''}
            {/* {record.disState == null ? <CommonTag type="daishenhe" /> : ''} */}
          </div>
        </div>
      ),
    },
    {
      title: '已还金额（元）',
      code: 'payAmount',
      width: 150,
    },
    {
      //   title: '剩余应还金额（元）',
      title: ( 
        <>
          <span>剩余应还金额（元）</span>
          <Popover content={<div style={{ width: '200px' }}>账期应还金额是正数，代表用户需要还款；如果是负数，代表是商户需要退还用户的钱</div>} placement="topLeft" trigger="hover">
            <span style={{ textIndent: '6px', cursor: 'pointer' }}><IconFont type='iconwenhao1' /></span>
          </Popover>
        </>
      ),
      code: 'lastAmount',
      width: 180,
    },
    {
      title: '备注',
      code: 'remark',
      width: 150,
    },
    {
      title: '操作',
      code: 'endTime',
      width: 220,
      lock: true,
      render: (text, record) => {
        return (
          <>
            <span className="opera-span-common">
              <span onClick={() => getDetail(record)}>账单明细</span>
              <i>|</i>
              <span onClick={() => openDetailPage({ ...record, type })}>对账单</span>
              <i>|</i>
              <Button disabled={record?.orderAmount < 0 ? true : false} style={{ fontSize: '12px', padding: 0 }} type="link" onClick={() => getRepayment(record)}>还款</Button>
              <i>|</i>
              {record.disState == 0 ? (
                <>
                  <Button disabled={record?.orderAmount < 0 ? true : false} style={{ fontSize: '12px', padding: 0 }} type="link" onClick={() => editBill(record)}>修改优惠</Button>
                  <i>|</i>
                  <Button disabled={record?.orderAmount < 0 ? true : false} style={{ fontSize: '12px', padding: 0 }} type="link" onClick={() => revokeBill(record)}>撤销优惠</Button>
                  <i>|</i>
                </>
              ) : (
                <>
                  <Button disabled={record?.orderAmount < 0 ? true : false} style={{ fontSize: '12px', padding: 0 }} type="link" onClick={() => applyBill(record)}>申请优惠</Button>
                  <i>|</i>
                </>
              )}
              <span onClick={() => getInformation(record)}>详情</span>
            </span>
          </>
        );
      },
    },
  ];

  const columns2 = [
    //未出账期
    {
      title: '合同编号',
      code: 'contractNo',
      width: 160,
    },
    {
      title: '供应商',
      code: 'storeName',
      width: 100,
    },
    {
      title: '出账时间',
      code: 'billsOutDay',
      width: 150,
    },
    {
      title: '剩余可用金额（元）',
      code: 'avablesAmount',
      width: 150,
    },
    {
      title: '订单占用总额（元）',
      code: 'notBookInAmount',
      width: 150,
      render: (text, record) => {
        return (
          <>
            <span className="m20">{text}</span>
            <span className="opera-span-common">
              <span onClick={() => getDetail1(record)}>
                账单明细
              </span>
            </span>
          </>
        );
      },
    },
    {
      //   title: '应还金额（元）',
      title: ( 
      <>
        <span>应还金额（元）</span>
        <Popover content={<div style={{ width: '200px' }}>账期应还金额是正数，代表用户需要还款；如果是负数，代表是商户需要退还用户的钱</div>} placement="topLeft" trigger="hover">
          <span style={{ textIndent: '6px', cursor: 'pointer' }}><IconFont type='iconwenhao1' /></span>
        </Popover>
      </>
      ),
      code: 'repamentAmount',
      width: 180,
      render: (text, record) => {
        return (
          <>
            <span className="m20">{text}</span>
            <span className="opera-span-common">
              <span onClick={() => getDetail2(record)}>
                账单明细
              </span>
              <i>|</i>
              <span onClick={() => openDetailPage({ ...record, type })}>对账单</span>
            </span>
          </>
        );
      },
    },
    {
      title: '操作',
      code: 'endTime',
      width: 120,
      lock: true,
      render: (text, record) => {
        return (
          <>
            <span className="opera-span-common">
              <span onClick={() => getAdvance(record)}>提前出账</span>
            </span>
          </>
        );
      },
    },
  ];

  const columns3 = [
    {
      title: '合同编号',
      code: 'contractNo',
      width: 200,
    },
    {
      title: '供应商',
      code: 'storeName',
      width: 100,
    },
    {
      title: '期数',
      code: 'period',
      width: 50,
    },
    {
      title: '出账时间',
      code: 'createTime',
      width: 150,
    },
    {
      title: '最终还款日',
      code: 'repaymentTime',
      width: 150,
    },
    {
      title: '还款时间',
      code: 'squareTime',
      width: 150,
    },
    {
      title: '逾期（天）',
      code: 'duePastDayNum',
      width: 80,
    },
    {
      title: '优惠金额（元）',
      code: 'discountAmount',
      width: 160,
    },
    {
      //   title: '已还金额（元）',
      title: (  <>
        <span>已还金额（元）</span>
        <Popover content={<div style={{ width: '200px' }}>账期应还金额是正数，代表用户需要还款；如果是负数，代表是商户需要退还用户的钱</div>} placement="topLeft" trigger="hover">
          <span style={{ textIndent: '6px', cursor: 'pointer' }}><IconFont type='iconwenhao1' /></span>
        </Popover>
      </>
      ),
      code: 'realPayAmount',
      width: 150,
    },
    {
      title: '操作',
      code: 'endTime',
      width: 180,
      lock: true,
      render: (text, record) => {
        return (
          <span className="opera-span-common">
            <span onClick={() => getDetail(record)}> 账单明细</span>
            <i>|</i>
            <span onClick={() => openDetailPage({ ...record, type })}>对账单</span>
            {
              !!record?.hasZxl && (
                <>
                  <i> | </i>
                  <span onClick={() => getZxlDetailsFunc(record.id)}><SafetyCertificateOutlined />账单结清证明</span>
                </>
              )
            }
          </span>
        );
      },
    },
  ];

  //至信链接口详情
  const getZxlDetailsFunc = async (id) => {
    setLoading(true);
    const { data, success } = await getZxlDetailsOp({ id });
    if (success) {
      setDetail(data);
    }
    setLoading(false);
  }

  //表格数据
  const TableProps = {
    data,
    columns: type == '1' ? columns1 : type == '2' ? columns2 : columns3,
    handleRowKey(record) {
      return record.id || record.contractNo + record.storeName + record.billsOutDay;
    },
    scroll: { x: 540 },
  };

  //表格组件
  const TableRenderProps = {
    data,
    columns: type == '1' ? columns1 : type == '2' ? columns2 : columns3,
    style: {
      height: `calc(100vh - ${headerHeight + 270}px)`
    },
    pageConfig: {
      pages,
      handlePageSize(page, size) {
        changePages(page,size);
      }
    }
  }

  //查看账单明细数据
  const detailProps = {
    detailVisible,
    record,
    type,
    orderStatus,
    handleCancel() {
      setDetailVisible(false);
    },
  };

  //查看详情弹窗数据
  const informationProps = {
    visible: informationVisible,
    record,
    handleCancel() {
      setInformationVisible(false);
    },
  };

  //申请/修改优惠账期
  const applyBillPeriodProps = {
    ApplyBillConfig,
    record,
    handleCancel() {
      handleSetApplyBillConfig(false);
    },
    handleOk(val) {
      handleApplyDiscount(ApplyBillConfig.type, val, record);
    },
  };

  // 账单明细
  const getDetail = (record) => {
    setOrderStatus('3');
    setDetailVisible(true);
    setRecord(record);
  };

  // 查看详情
  const getInformation = (record) => {
    setInformationVisible(true);
    setRecord(record);
  };

  //申请优惠
  const applyBill = (record) => {
    setRecord(record);
    handleSetApplyBillConfig(true, '申请优惠账期', 'add');
  };

  //修改优惠
  const editBill = (record) => {
    setRecord(record);
    handleSetApplyBillConfig(true, '修改优惠账期', 'edit');
  };

  //撤销
  const revokeBill = (record) => {
    Modal.confirm({
      title: '撤销优惠账期',
      icon: <ExclamationCircleOutlined />,
      content: '确定要撤销优惠账期吗？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        handleRevokeDiscount(record);
      },
    });
  };

  // 订单总额跳转
  const getDetail1 = (record) => {
    setOrderStatus('1');
    setDetailVisible(true);
    setRecord(record);
  };

  // 应还跳转
  const getDetail2 = (record) => {
    setOrderStatus('2');
    setDetailVisible(true);
    setRecord(record);
  };

  const { id, title, userAccount, storeName, amount, evId, evHash, txHash, createTime, blockHeight, } = zxlDetail || {};

  const bradgeTime = useMemo(() => {
    if (createTime) {
      // const time = new Date(createTime),
      //       year = time.getFullYear(),
      //       month = time.getMonth() + 1,
      //       day = time.getDate();
      // return `${year}年${month}月${day}日`
      return createTime.split(' ')[0].replace('-', '年').replace('-', '月') + '日';
    }
  }, [createTime])

  return (
    <>
      <TableRender {...TableRenderProps} />
      {detailVisible && <PeriodDetails {...detailProps} />}
      <PeriodInformation {...informationProps} />
      <ApplyBillPeriod {...applyBillPeriodProps} />
      <div className={styles.zxinChainCover} onClick={() => setDetail(false)} style={{ opacity: zxlDetail ? 1 : 0, visibility: zxlDetail ? true : 'hidden' }}>
        <div className={styles.zxinChainWrapper} onClick={(e) => e.stopPropagation()}>
          <p className={styles.idBox}>存证ID：{evId}</p>
          <h5>存证信息</h5>
          <div className={styles.infoBox}>
            <p>信息类标：{title}</p>
            <p>还款方：{userAccount}</p>
            <p>收款方：{storeName}</p>
            <p>金额：{formatAmount(amount)} 元</p>
            <p>状态：已结清</p>
          </div>
          <h5>存证摘要</h5>
          <div className={styles.infoBox}>

            <p style={{ display: "flex" }}>
              <span style={{ width: "102px" }}>电子存证hash：</span>
              <span style={{ flex: 1, wordBreak: 'break-word' }}>{evHash}</span>
            </p>
            <p style={{ display: "flex" }}>
              <span style={{ width: "116px" }}>至信链交易hash：</span>
              <span style={{ flex: 1, wordBreak: 'break-word' }}>{txHash}</span>
            </p>
            <p>可信存正时间：{createTime}</p>
            <p>区块高度：{blockHeight}</p>
            <p>可查数据地址：https://www.zxinchain.com/evidence</p>
          </div>
          <div className={styles.imgBox}>
            <div className={styles.qrCodeBox}>
              <QRCode value={`${window.location.origin}/?id=${id}#/blank/zxinchain`} size={104} />
              <span>扫码查看在线证书</span>
            </div>
            <div className={styles.bradgeBox}>
              <img src="https://imgniu.zhaojiafang.com/front-web/zxlBradge.png" alt="" />
              <span>{bradgeTime}</span>
            </div>
          </div>
          <span className={styles.footerDesc}>信息永久受区块链保护，任何人无法篡改</span>
        </div>
      </div>
      <CommonLoading loading={loading} />
    </>
  );
};

export default PeriodTable;
